﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using FranceTriple.Dal;
using System.Web;

namespace TeamFranceTriple
{
    public partial class ForumTopicDetail : BaseUserControl
    {
        private string FirstPositionLocalized = "FirstPosition".ToLocalizedString();
        private string TopicIsNotStickyLocalized = "TopicIsNotSticky".ToLocalizedString();

        private Int32 UserRightLevel { get; set; }

        public Int32 ForumCategoryId { get; private set; }
        public Int32 ForumTopicId { get; private set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            //Déterminer ForumCategoryId
            if (!IsPostBack)
            {
                if (Page.RouteData.Values["categoryid"] == null)
                    ForumCategoryId = 0;
                else
                {
                    ForumCategoryId = Int32.Parse(Page.RouteData.Values["categoryid"].ToString());
                    if (ForumCategoryId > 0)
                    {
                        ValidCategory(ForumCategoryId);
                    }
                }
            }
            else
            {
                Int32 categoryId;
                bool result = Int32.TryParse(CategoryDropDownList.SelectedValue, out categoryId);
                if (result)
                {
                    ForumCategoryId = categoryId;
                    ValidCategory(ForumCategoryId);
                }
                else
                    throw new HttpException(404, String.Format("This category don't exists: {0}", CategoryDropDownList.SelectedValue));
            }

            //Déterminer ForumTopicId
            if (Page.RouteData.Values["topicid"] == null)
                ForumTopicId = 0;
            else
            {
                ForumTopicId = Int32.Parse(Page.RouteData.Values["topicid"].ToString());
            };
            ForumTopicSetEntityDataSource1.WhereParameters["ForumTopicIdParam"].DefaultValue = ForumTopicId.ToString();

            CategoryDropDownList.Items.Clear();
            CategoryDropDownList.DataSource = UserAccessDal.GetForumCategoryAuthorRightLookup((Session["AnonymousID"] == null) ? String.Empty : Session["AnonymousID"].ToString());
            CategoryDropDownList.DataBind();

            if(ForumCategoryId>0)
                CategoryDropDownList.SelectedValue = ForumCategoryId.ToString();

            if (!IsPostBack && ForumTopicId > 0)
                SetEditMode();

            //Todo: faire varier le Title de la page qui est non-accessible par les moteurs de recherche
            this.Page.Title = prefixTitle + "";
        }

        private void ValidCategory(int ForumCategoryId)
        {
            // Vérifier que la catégorie existe                
            ForumCategory ThisCategory = ForumCategoryDal.GetEntity(ForumCategoryId);
            if (ThisCategory == null)
                throw new HttpException(404,String.Format( "This category don't exists: {0}", ForumCategoryId.ToString()));

            // Vérifier que l'utilisateur au moins les droits d'auteur sur la category
            this.UserRightLevel = UserAccessDal.UserRightLevel(ForumCategoryId, ((Session["AnonymousID"] == null) ? String.Empty : Session["AnonymousID"].ToString()));
            if (this.UserRightLevel < RightLevel.Author)
                Response.Redirect(String.Format("~/{0}/connexion/?returnurl=~{1}",ThisMaster.Requester.Culture, Request.RawUrl));
        }

        private void SetEditMode()
        {
            var ForumTopicEditing = ForumTopicDal.GetEntity(ForumTopicId);
            LabelTopicTextBox.Text = ForumTopicEditing.LabelForumTopic.HtmlToText();

            CategoryDropDownList.SelectedValue = ForumCategoryDal.GetCategoryIdByTopicId(ForumTopicId).ToString();
            ForumTopicSetEntityDataSource1.WhereParameters["ForumCategoryIdParam"].DefaultValue = CategoryDropDownList.SelectedValue;
            InsertBeforeStickyTopicDropDownList.DataBind();

            InsertBeforeStickyTopicDropDownList.SelectedValue = (ForumTopicEditing.OrderForumTopic == 0) ?
                                                "0" : (ForumTopicEditing.OrderForumTopic + 10).ToString();
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {

        }

        protected void CategoryDropDownList_SelectedIndexChanged(object sender, EventArgs e)
        {
            ForumTopicSetEntityDataSource1.WhereParameters["ForumCategoryIdParam"].DefaultValue = CategoryDropDownList.SelectedValue;
        }

        protected void InsertBeforeStickyTopicDropDownList_OnDataBound(object sender, EventArgs e)
        {
            if (InsertBeforeStickyTopicDropDownList.Items.Count > 0)
                InsertBeforeStickyTopicDropDownList.Items.Insert(0, new ListItem() { Text = FirstPositionLocalized, Value = (Int32.Parse(InsertBeforeStickyTopicDropDownList.Items[0].Value) + 10).ToString() });
            else
                InsertBeforeStickyTopicDropDownList.Items.Insert(0, new ListItem() { Text = FirstPositionLocalized, Value = "10" });

            InsertBeforeStickyTopicDropDownList.Items.Insert(0, new ListItem() { Text = TopicIsNotStickyLocalized, Value = "0" });
        }

        protected void AddTopicPopupButton_Click(object sender, EventArgs e)
        {
            if (!this.Page.IsValid) return;

            ForumCategoryId = Int32.Parse(CategoryDropDownList.SelectedValue);
            ValidCategory(ForumCategoryId);

            ForumTopic forumTopicToUpdate = new ForumTopic()
            {
                Id = ForumTopicId,
                LabelForumTopic = LabelTopicTextBox.TextToHtml(),
                AuthorForumTopic = ThisMaster.Requester.Profile.UserName,
                NumberHasBeenSeenForumTopic = 0,
            };

            if (LabelTopicTextBox.Text != string.Empty)
            {
                forumTopicToUpdate.OrderForumTopic = Int32.Parse(InsertBeforeStickyTopicDropDownList.SelectedValue);
                //if (forumTopicToUpdate.OrderForumTopic != 0)
                //    forumTopicToUpdate.OrderForumTopic = Int32.Parse(InsertBeforeStickyTopicDropDownList.SelectedValue);

                //forumTopicToUpdate.OrderForumTopic = 0;

                // Route to MessageDetail for a Post
                // {culture}/messagedetail/post/{topicid}/{messageid}
                if (ForumTopicId == 0)
                {
                    forumTopicToUpdate.ForumCategory = ForumCategoryDal.GetEntity(ForumCategoryId);
                    ForumTopicId = ForumTopicDal.CreateEntity(forumTopicToUpdate);
                    Response.Redirect(String.Format("~/{0}/messagedetail/post/{1}/0/", ThisMaster.Requester.Culture, ForumTopicId));
                }
                else
                {
                    forumTopicToUpdate.ForumCategory = new ForumCategory() { Id = ForumCategoryId };
                    ForumTopicDal.UpdateEntity(forumTopicToUpdate);
                    Response.Redirect(String.Format("~/{0}/topic/bycategory/{1}", ThisMaster.Requester.Culture, ForumCategoryDal.GetCategoryIdByTopicId(ForumTopicId)));
                }

                ForumTopicId = 0;
                LabelTopicTextBox.Text = String.Empty;
                InsertBeforeStickyTopicDropDownList.DataBind();
            }
        }

    }
}